<?php

namespace app\admin\controller\slider_imgs;

use app\common\controller\Backend;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Sliderimgs extends Backend
{
    
    /**
     * Sliderimgs模型对象
     */
    protected $model = null;
    protected $noNeedRight=[];
    protected $noNeedLogin=[];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Sliderimgs');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->alias("i")
                ->where($where)
                ->where("i.status",1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                //->order("weigh desc")
                ->field ("i.id,i.number,i.title,href,src,i.city_id,i.school_id")
                ->alias("i")
                ->join("Slider s", "i.number = s.number", "LEFT")
                ->where("i.status",1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['number']=$this->model->getNumberTextAttr($list[$i]['number'],$list[$i]);
                $list[$i]['city_id']=model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['school_id']=model("School")->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $images = $this->request->post("images/a");
            $city_id = $this->auth->city_id;
            $school_id = $this->auth->school_id;

            
            // 验证位置编号是否选择
            if (empty($params['number'])) {
                $this->error('请先选择位置编号');
            }
            
            // 验证是否有图片数据
            if (empty($images) || !is_array($images)) {
                $this->error('请至少添加一张图片');
            }
            
            try {
                // 开启事务
                $this->model->startTrans();
                
                $datatime = date("Y-m-d H:i:s");
                $successCount = 0;
                
                // 遍历保存每个图片组
                foreach ($images as $index => $imageData) {
                    // 检查必要字段
                    if (empty($imageData['src'])) {
                        continue; // 跳过没有图片地址的项
                    }
                    
                    // 准备保存数据
                    $saveData = [
                        'number' => $params['number'],
                        'title' => isset($imageData['title']) ? trim($imageData['title']) : '',
                        'href' => isset($imageData['href']) ? trim($imageData['href']) : '',
                        'src' => trim($imageData['src']),
                        'create_time' => $datatime,
                        'update_time' => $datatime,
                        'city_id' => $city_id,
                        'school_id' => $school_id,
                        'status' => 1
                    ];
                    
                    // 数据权限处理
                    if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                        $saveData[$this->dataLimitField] = $this->auth->id;
                    }
                    
                    // 创建新的模型实例进行保存
                    $model = model('Sliderimgs');
                    
                    // 模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $model->validate($validate);
                    }
                    
                    // 使用 insertOrUpdate 方法，需要指定唯一标识字段
                    $result = $model->insertUpdate($saveData, ['number', 'title']); // 根据 number 和 title 字段判断是否存在
                    
                    if ($result !== false) {
                        $successCount++;
                    }
                }
                
                if ($successCount > 0) {
                    // 提交事务
                    $this->model->commit();
                    
                    // 使用return json输出标准成功格式
                    return json([
                        'code' => 1,
                        'msg' => "成功保存 {$successCount} 张图片",
                        'time' => time(),
                        'data' => null
                    ]);
                } else {
                    // 回滚事务
                    $this->model->rollback();
                    
                    return json([
                        'code' => 0,
                        'msg' => '没有有效的图片数据被保存',
                        'time' => time(),
                        'data' => null
                    ]);
                }
                
            } catch (\think\exception\PDOException $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            // 获取该位置编号下的所有图片
            $images = $this->model->where('number', $row['number'])
                ->order('id asc')
                ->select();
            
            $this->view->assign('row', $row);
            $this->view->assign('images', $images);
            return $this->view->fetch();
        }
        
        // POST 请求处理逻辑保持原有的批量更新逻辑
        $params = $this->request->post("row/a");
        $images = $this->request->post("images/a");
        
        // 验证位置编号是否选择
        if (empty($params['number'])) {
            $this->error('请先选择位置编号');
        }
        
        // 验证是否有图片数据
        if (empty($images) || !is_array($images)) {
            $this->error('请至少添加一张图片');
        }
        
        $number = $params['number'];
        
        // 开启事务
        $this->model->startTrans();
        try {
            // 先删除该位置编号下的所有图片
            $this->model->where('number', $number)->delete();
            
            $savedCount = 0;
            $datatime = date("Y-m-d H:i:s");
            
            foreach ($images as $index => $imageData) {
                // 检查图片数据是否完整
                if (!empty($imageData['src'])) {
                    $data = [
                        'number' => $number,
                        'title' => $imageData['title'] ?? '',
                        'href' => $imageData['href'] ?? '',
                        'src' => $imageData['src'],
                        'create_time' => $datatime,
                        'update_time' => $datatime
                    ];
                    
                    // 使用 insertOrUpdate 方法
                    $model = model('Sliderimgs');
                    $result = $model->insertOrUpdate($data, ['number', 'src']);
                    
                    if ($result !== false) {
                        $savedCount++;
                    }
                }
            }
            
            if ($savedCount > 0) {
                $this->model->commit();
                $this->success('成功更新 ' . $savedCount . ' 张图片');
            } else {
                $this->model->rollback();
                $this->error('没有有效的图片数据被保存');
            }
            
        } catch (\think\exception\PDOException $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        $pk = $this->model->getPk();
        $list = $this->model->where($pk, 'in', $ids)->select();
        
        $count = 0;
        $this->model->startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            $this->model->commit();
        } catch (\think\exception\PDOException $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        } catch (\think\Exception $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="";
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    $where="where 1=0";
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " or $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql="select id,title name from dev002_gxyusheng.fa_slider_imgs $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        //$tree = Tree::instance();
        //$tree->init($list, 'pid');
        //if(isset($keyValue)&&$keyValue!=""){
        //}else{
        //    $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
        //    //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        //}

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_slider_imgs $where")[0];
        return json(array("list" => $list, "total" => $total['c']));
    }

    /**
     * 获取指定位置编号的所有图片数据
     */
    public function getImagesByNumber()
    {
        if ($this->request->isPost()) {
            $number = $this->request->post('number');
            
            if (!$number) {
                $this->error('位置编号不能为空');
            }
            
            try {
                $images = $this->model->where('number', $number)
                    ->order('id asc')
                    ->select();
                
                $this->success('获取成功', null, $images);
            } catch (\Exception $e) {
                $this->error('获取失败: ' . $e->getMessage());
            }
        } else {
            $this->error('非法请求');
        }
    }



}
